﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace SuperKit {
    class NetworkKit {

        public static int GetFreePort() {
            var used = PortIsUsed();
            for (int i = 10000; i < 65535; i++) {
                if (!IsUsed(i, used)) {
                    return i;
                }
            }
            return 0;
        }

        private static bool IsUsed(int port, List<int> used) {
            foreach (var i in used) {
                if (i == port) {
                    return true;
                }
            }
            return false;
        }

        /// <summary>        
        /// 获取操作系统已用的端口号 
        /// </summary>        

        /// <returns></returns> 
        public static List<int> PortIsUsed() {

            //获取本地计算机的网络连接和通信统计数据的信息            

            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();

            //返回本地计算机上的所有Tcp监听程序            

            IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners();

            //返回本地计算机上的所有UDP监听程序            

            IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();

            //返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。            

            TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

            List<int> allPorts = new List<int>();

            foreach (IPEndPoint ep in ipsTCP) {

                allPorts.Add(ep.Port);

            }

            foreach (IPEndPoint ep in ipsUDP) {

                allPorts.Add(ep.Port);

            }

            foreach (TcpConnectionInformation conn in tcpConnInfoArray) {

                allPorts.Add(conn.LocalEndPoint.Port);

            }

            return allPorts;
        }
    }
}
